package pers.vic.sso.server.session;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import pers.vic.boot.util.CookieUtil;
import pers.vic.sso.common.constant.SsoConstant;
import pers.vic.sso.common.model.SsoUser;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:
 *     全局tgt管理器
 * @author Vic.xu
 * @date 2021-11-01 9:20
 */
@Component
public class SessionManager {

    @Resource
    private TicketGrantingTicketManager ticketGrantingTicketManager;

    @Resource
    private AccessTokenManager accessTokenManager;

    /**
     * 创建全局tgt  并存到cookie
     * @param user
     * @param request
     * @param response
     * @return
     */
    public String createTgt(SsoUser user, HttpServletRequest request, HttpServletResponse response) {
        String tgt = getCookieTgt(request);
        //如果cookie中不存在tgt则生成，并保存到cookie
        if (StringUtils.isEmpty(tgt)) {
            tgt = ticketGrantingTicketManager.generate(user);
            CookieUtil.set(response, SsoConstant.TGC, tgt, true);
            return tgt;
        }

        // 如果不存在tgt，或者过期了则重新存储起来
        if (ticketGrantingTicketManager.getAndRefresh(tgt) == null) {
            ticketGrantingTicketManager.storage(tgt, user);
            return tgt;
        }
        //如果存在，则直接返回(上一步中已经Refresh过期时间了)
        return tgt;

    }

    /**
     * 从cookie中获取全局票据
     * @param request
     * @return
     */
    private String getCookieTgt(HttpServletRequest request) {
        String tgt = CookieUtil.getValue(request, SsoConstant.TGC);
        return tgt;
    }

    /**
     * 从cookie中获取tgt
     * @param request
     * @return
     */
    public String getTgt(HttpServletRequest request) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isEmpty(tgt) || ticketGrantingTicketManager.getAndRefresh(tgt) == null) {
            return null;
        }
        return tgt;
    }

    /**
     * 在客户端发出退出登录请求时,删除凭证、cookie并通知其他客户端退出登录
     * @param request
     * @param response
     */
    public void invalidate(HttpServletRequest request, HttpServletResponse response) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isEmpty(tgt)) {
            return;
        }
        //1 删除登录凭证
        ticketGrantingTicketManager.remove(tgt);
        //2 删除cookie
        CookieUtil.remove(request, response, SsoConstant.TGC);
        // 3删除所有tgt对应的调用凭证，并通知客户端登出注销本地session
        accessTokenManager.remove(tgt);

    }
}
